package vip.liux.backend.adapter.web;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import vip.liux.application.dots.PagedResultDto;
import vip.liux.backend.application.service.pay.PayWalletService;
import vip.liux.backend.application.service.pay.dto.wallet.PayWalletDto;
import vip.liux.backend.application.service.pay.dto.wallet.PayWalletQueryDto;
import vip.liux.backend.application.service.pay.dto.wallet.PayWalletUpdateBalanceDto;
import vip.liux.contracts.shared.enums.pay.PayWalletBizType;

import javax.validation.Valid;
import java.math.BigDecimal;

import static vip.liux.contracts.shared.enums.ErrorCode.WALLET_NOT_FOUND;
import static vip.liux.contracts.shared.util.ServiceExceptionUtil.exception;

@RestController
@RequestMapping("/api/pay/wallet")
public class PayWalletController {

    private static final Logger log = LoggerFactory.getLogger(PayWalletController.class);
    @Resource
    private PayWalletService payWalletService;

    /**
     * 冻结资金
     */
    @PostMapping("/freeze")
    public void freeze(@RequestParam Long walletId, @RequestParam BigDecimal amount) {
        payWalletService.freezePrice(walletId, amount);
    }

    /**
     * 解冻资金
     */
    @PostMapping("/unfreeze")
    public void unfreeze(@RequestParam Long walletId, @RequestParam BigDecimal amount) {
        payWalletService.unfreezePrice(walletId, amount);
    }

    /**
     * 获取钱包详情
     *
     * @param uid 用户编号
     * @return 钱包信息
     */
    @GetMapping("/detail/uid/{uid}")
    public PayWalletDto getOrCreateWallet(@PathVariable String uid) {
        return payWalletService.getOrCreateWallet(uid);
    }

    /**
     * 分页查询会员钱包
     *
     * @param input 查询参数
     * @return 分页结果
     */
    @GetMapping("/page")
    public PagedResultDto<PayWalletDto> getWalletPage(PayWalletQueryDto input) {
        return payWalletService.getWalletPage(input);
    }

    /**
     * 更新钱包余额
     *
     * @param input 更新请求参数
     */
    @PutMapping("/update-balance")
    public void updateWalletBalance(@Valid @RequestBody PayWalletUpdateBalanceDto input) {
        // 获得用户钱包
        PayWalletDto wallet = payWalletService.getOrCreateWallet(input.getUid());
        if (wallet == null) {
            log.error("[updateWalletBalance]，updateReqVO({}) 用户钱包不存在.", input);
            throw exception(WALLET_NOT_FOUND);
        }

        // 更新钱包余额
        payWalletService.addWalletBalance(wallet.getId(), String.valueOf(input.getUid()),
                PayWalletBizType.UPDATE_BALANCE, input.getBalance());
    }
}